#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent),
    ui(new Ui::MainWindow),
    multicastChat(new MulticastChat)  // 创建 MulticastChat 实例
{
    ui->setupUi(this);
//    connect(ui->pushButton,&QPushButton::clicked,this,[=](){
//        qDebug() << "hello";
//    });
    // 将发送按钮的点击信号连接到槽函数
    connect(ui->pushButton, &QPushButton::clicked, this, &MainWindow::on_sendButton_clicked);

    // 将接收线程的信号连接到更新 chatListView 的槽函数
    connect(multicastChat, &MulticastChat::recvData, this, &MainWindow::handleReceivedData);

//    connect(multicastChat, &MulticastChat::recvData, this, [=](){
//        qDebug() << "receive data";
//    });
    QListView *listView = ui->chatListView;
    QScrollArea *scrollArea = ui->scrollArea;
    // 创建一个标准项模型
    QStandardItemModel *model = new QStandardItemModel(this);

    // 设置模型给 QListView
    ui->chatListView->setModel(model);


    // 将滚动条的信号连接到槽函数，当滚动条滚动时更新 QListView 的滚动位置
    connect(scrollArea->verticalScrollBar(), &QScrollBar::valueChanged, this, [=](int value){
        qDebug() << "Scrollbar value changed:" << value;
        listView->verticalScrollBar()->setValue(value);
    });


    multicastChat->startChat();
}

MainWindow::~MainWindow()
{
    // 停止聊天并删除 MulticastChat 实例
    multicastChat->stopChat();
    delete ui;
    delete multicastChat;
}
void MainWindow::handleReceivedData(const QString& message)
{
    // 从模型中获取QListView的模型
    QStandardItemModel *model = qobject_cast<QStandardItemModel*>(ui->chatListView->model());
    if (!model) {
        qDebug() << "Failed to retrieve model. QListView model is null.";
        return;
    }


    // 创建一个标准项，用于显示接收到的消息
    QStandardItem *item = new QStandardItem(message);

    // 将标准项添加到模型中
    model->appendRow(item);
}
void MainWindow::on_sendButton_clicked()
{
    // 从行编辑中获取消息并发送
    QString message = ui->lineEdit->text();
    multicastChat->sendMessage(message);
    ui->lineEdit->clear();
}
